<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path;
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
<title>校车申请-云校通-教师</title>
<jsp:include page="/WEB-INF/page/common/_header.jsp"></jsp:include>
<body ontouchstart id="tjjsqj">
	<div class="weui_tab tab-bottom">
		<div class="weui-header bg-blue"> 
	  		<div class="weui-header-left">
	  		 <a onclick="back()" href="javascript:;" class="icon icon-109 f-white">返回</a > 
	  		</div>
	    	<h1 class="weui-header-title">校车申请</h1>
	    </div>
		<div class="weui_tab_bd">
	        <div class="weui_cells" style="margin-top:0;">
				<div class="weui_cell">
					<div class="weui_cell_hd">
						<label class="weui_label">用车事由</label>
					</div>
					<div class="weui_cell_bd weui_cell_primary">
						<input type="text" class="weui_input" id="useCarReason" placeholder="请填写用车是由(必填)"/>
					</div>
				</div>
				<div class="weui_cell">
					<div class="weui_cell_hd">
						<label class="weui_label">人数</label>
					</div>
					<div class="weui_cell_bd weui_cell_primary">
						<input type="number" pattern="[0-9]*" class="weui_input" id="number" placeholder="请填写人数(必填)"/>
					</div>
				</div>
				<div class="weui_cell">
					<div class="weui_cell_hd">
						<label class="weui_label">开始时间</label>
					</div>
					<div class="weui_cell_bd weui_cell_primary">
						<input type="datetime-local" class="weui_input" id="startDate" />
					</div>
				</div>
				<div class="weui_cell">
					<div class="weui_cell_hd">
						<label class="weui_label">结束时间</label>
					</div>
					<div class="weui_cell_bd weui_cell_primary">
						<input type="datetime-local" class="weui_input" id="endDate" />
					</div>
				</div>
				<div class="weui_cell">
					<div class="weui_cell_hd">
						<label class="weui_label">目的地</label>
					</div>
					<div class="weui_cell_bd weui_cell_primary">
						<input type="text" class="weui_input" id="destination" placeholder="请填写目的地(必填)"/>
					</div>
				</div>
			</div>
	        
			<div class="weui_cells  weui_cells_access">
				<div class="weui_cell" id="check">
					<div class="weui_cell_bd absolut">
	                    <p>审批人</p>
	                </div>
				</div>
				<div class="gzsp_wrap">
					<ul></ul>
					<div><span id="addBtn" class="add"></span></div>
				</div>
			</div>
			
	       <div class="weui_btn_area mb55">
		        <a href="javascript:" class="weui_btn bg-blue" id="btnSubmit">提交申请</a>
		    </div>
		</div>
	</div>
	
	<!--弹窗-->				
	<div class="weui_mask ueureiu weui_mask_visible" style="display: none;z-index:600">
	</div>
	<!--End弹窗-->
	
	<!-- 老师组织架构 start-->
	<div id="ls_div_box" class="weui_tab tab-bottom" style="display:none;z-index: 600;background-color: #f8f8f8;">
		<div class="weui_tab_bd">
	        <div class="weui-header bg-blue"> 
	        	<div class="weui-header-left" id="teacherBack"> <a class="icon icon-109 f-white">取消</a>  </div>
				<h1 class="weui-header-title">${config.appName}组织架构</h1>
			</div>
	        
	        <!--下拉选择-->
	        <div class="page-bd">  
		         <ul id="teacherList">
		     	 </ul>
		    </div>
	    	<script id="teacher-table-template" type="text/x-handlebars-template">	
 				{{#each list}}
					<li class="list1">
		                <div class="weui-flex">
		                   	<p class="weui-flex-item js-category"> {{groupName}}</p>
		                    <span class="js-category"><i class="icon icon-74"></i> 下级</span>
		                </div>
		                <div class="page-category js-categoryInner">
							<div class="weui_cells" style="margin: 0;">
								<ul class="list_3">
								{{#each subList}}
						            <li><div class="weui_cell_hd list_c3" style="display: inline-flex;padding-left: 10px;">
											<label class="weui_cells_checkbox weui_check_label" style="padding-right: 15px;" for="{{groupId}}_{{teacherId}}">
												<input type="checkbox" class="weui_check" value="{{teacherId}}" id="{{groupId}}_{{teacherId}}">
					        					<i class="weui_icon_checked"></i>
											</label>
											<label class="tea_name">{{teacherName}}</label>
										</div>
									</li>
								{{/each}}
								</ul>
							</div>
		                </div>
		            </li>
				{{/each}}
			</script>
	    <!--End下拉选择-->
		</div>
	</div>
</body>
<jsp:include page="/WEB-INF/page/common/_footer.jsp"></jsp:include>
<script>
	var teacherData = {};
	$(function() {
		initApprover();
		$('#btnSubmit').on('click', function() {
			submit();
		});
    	//老师组织架构返回
		$("#teacherBack").click(function() {
			$('.ueureiu').hide();
			$("#ls_div_box").hide();
		});
		//老师组织架构弹出
      	$("#addBtn").click(function() {
      		//上下级拉动
    		$("#teacherList .js-category").each(function(i, v) {
        		v.removeEventListener("click", categoryClick, false);
        		v.addEventListener('click', categoryClick);
        	})
      		$('.ueureiu').show();
      		$("#ls_div_box").show();
			$(".list_c3 input").change(function() {
				var obj = $(this);
				var otherChecked = obj.closest("li").siblings().find("input:checked");
				if(otherChecked.length > 0) {
					otherChecked[0].checked = false
				}
				var name = obj.closest(".list_c3").find(".tea_name").html();
				$(".gzsp_wrap>ul").html("");
				$(".gzsp_wrap>ul").append("<li><div class='gzsp'><span>"+name.substr(name.length-2,name.length)+"</span><i data-id='"+obj.val()+"'>"+name+"</i></div></li>");
				$("#teacherBack").click();
			});
      	})
	});
	function submit() {
		var useCarReason = $("#useCarReason").val();
		if(useCarReason.length == 0) {
			$.alert("请填写加班事由!","");
			return;
		}
		var number = $("#number").val();
		if(number.length == 0) {
			$.alert("请填写人数!","");
			return;
		}
		var startDate = $("#startDate").val();
		if(startDate.length == 0) {
			$.alert("请选择开始时间!","");
			return;
		}
		var endDate = $("#endDate").val();
		if(endDate.length == 0) {
			$.alert("请选择结束时间!","");
			return;
		}
		var destination = $("#destination").val();
		if(destination.length == 0) {
			$.alert("请填写目的地!","");
			return;
		}
		var attachIds = "";
		var aObj = $($(".gzsp_wrap").find(".gzsp i"));
		var approverId = emptyToNull(aObj.attr("data-id"));
		if(approverId == null) {
			$.alert("请选择审批人", "");
			return;
		}
		$.confirm("提交申请后2个小时内可以撤销申请", "确认提交申请?", function() {
			$.ajax({
				url: basePath + '/ls/work/approval/apply/submit',
				type: 'post',
				dataType: 'json',
				data: {
					approver: aObj.html(),
					approverId: approverId,
					number: number,
					approvalType: '${approvalType}',
					useCarReason: useCarReason,
					startDate: startDate.replace("T"," "),
					endDate: endDate.replace("T"," "),
					destination: destination,
					attachIds: attachIds
				},
				success: function(data) {
					if (data.code == '000') {
						$.toast("申请提交成功！");
						setTimeout(function(){
							window.location.href = basePath + "/ls/work/approval?v=" + new Date().getTime();
						}, 1000);
					} else {
						$.toptips(data.msg);
					}
				}
			});
		}, function() {
        });
	}
	function initApprover() {
		$.ajax({
			url: basePath + '/ls/work/approval/approver',
			type: 'post',
			dataType: 'json',
			data: {
				approvalType: '${approvalType}'
			},
			success: function(data) {
				if(data.data.approvalerId != null && data.data.approvalerId != undefined){
					var approvalers = data.data.approvaler.split(",");
					if(approvalers.length == 1) {
						$(".gzsp_wrap").find("div").remove();
						var name = approvalers[0];
						$(".gzsp_wrap>ul").append("<li><div class='gzsp'><span>"+name.substr(name.length-2,name.length)+"</span><i data-id='"+data.data.approvalerId+"'>"+name+"</i></div></li>");
					}else {
						var approvalerIds = data.data.approvalerId.split(",");
						var html = '<div class="weui_cells" style="margin: 0;"><ul class="list_3">';
						for(var i in approvalers) {
							html += '<li><div class="weui_cell_hd list_c3" style="display: inline-flex;padding-left: 10px;">\
											<label class="weui_cells_checkbox weui_check_label" style="padding-right: 15px;" for="tea_'+approvalerIds[i]+'">\
												<input type="checkbox" class="weui_check" value="'+approvalerIds[i]+'" id="tea_'+approvalerIds[i]+'">\
					        					<i class="weui_icon_checked"></i>\
											</label>\
											<label class="tea_name">'+approvalers[i]+'</label>\
										</div>\
									</li>';
						}
						html += '</ul></div>';
						$('#teacherList').html(html);
					}
				}else {
					teacherData.list = data.data;
	 				loadTeacherHtml(teacherData);
				}
			}
		});
	}
	function loadTeacherHtml(teacherData) {
		var myTemplate = Handlebars.compile($("#teacher-table-template").html());
			Handlebars.registerHelper("equal", function(v1,v2,options) {
    		if(v1 == v2) {
    			//满足添加继续执行
    			return options.fn(this);
    		}else {
    			//不满足条件执行{{else}}部分
    			return options.inverse(this);
    		}
    	});
		$('#teacherList').html(myTemplate(teacherData));
	}
	function categoryClick() {
		$parent = $(this).closest('li');
		if($parent.hasClass('js-show')){
            $parent.removeClass('js-show');
            $parent.find('i').removeClass('icon-35').addClass('icon-74');
        }else{
            $parent.siblings().removeClass('js-show');
            $parent.addClass('js-show');
            $parent.siblings().find('i').removeClass('icon-35').addClass('icon-74');
            $parent.find('i').removeClass('icon-74').addClass('icon-35');
        }
	}
	
	/* document.querySelector('#imgid').onchange = function(e) {
		var files = e.target.files;
		var len = files.length;
		for (var i=0; i < len; i++) {
			lrz(files[i], {
				width:1080
			})
			.then(function (rst) {
				var xhr = new XMLHttpRequest();
	            xhr.open('POST', basePath + "/ls/attchment/upload/lrz");
	            xhr.onload = function () {
	                if (xhr.status === 200) {
	                	var obj = JSON.parse(xhr.response)
	                	$("#img1").append('<li class="weui_uploader_file" data-id="'+obj.data.id+'" onclick="imgClick(this)" style="margin-right:0;margin-bottom:10px;position: relative;"><div class="img-del" onclick="imgDel(this)"><span class="icon icon-26"></span></div><img src="'+ rst.base64 +'"/></li>')
	                }
	            };
	            xhr.onerror = function () {
	            	alert("上传异常");
	            };
	            xhr.upload.onprogress = function (e) {
	                // 上传进度
	                var percentComplete = ((e.loaded / e.total) || 0) * 100;
	            };
	            // 添加参数
	            rst.formData.append('attachmentName', rst.origin.name);
	            rst.formData.append('attachmentSize', rst.fileLen);
	            rst.formData.append('baseData', rst.base64);
	            rst.formData.append('attachmentType', "image");
	            rst.formData.append('relationType', "workApproval");
	            // 触发上传
	            xhr.send(rst.formData);
	            return rst;
			})
	        .always(function () {
	            // 不管是成功失败，都会执行
	        });
			;
		}
	} */

	//拍照或从手机相册中选图接口
	$('#filePicker').on('click', function () {
		wx.chooseImage({
		    count: 9,
		    needResult: 1,
		    sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
		    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
		    success: function (res) {
		   		var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
		   		wxuploadImage(localIds);
		    },
		    fail: function (res) {
		        alterShowMessage("操作提示", JSON.stringify(res), "1", "确定", "", "", "");
		    }
		
		});
	});
	function wxuploadImage(localIds) {  
		var localId = localIds.pop();
		wx.uploadImage({  
		    localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得  
		    isShowProgressTips: 1, // 默认为1，显示进度提示  
		    success: function (res) {  
		        mediaId = res.serverId; // 返回图片的服务器端ID
		        wechatMediaDownload(mediaId);
		        if(localIds.length > 0){
		        	wxuploadImage(localIds);
		        }
		    },  
		    fail: function (error) {  
		        alert(Json.stringify(error));  
		    }  
		});
	}  
	function wechatMediaDownload(mediaId) {
		var params = {};
		params.mediaId = mediaId;
		params.attachmentType = "image";
		params.relationType = "workApproval";
		$.ajax({
			url : basePath + "/ls/attchment/upload/wx",
			type : "post",
			data : params,
			dataType : "json",
			async : false,
			success : function(data) {
				if(data.code != '000') {
					$.toast(data.msg, "cancel");
				}else {
					$('#img1').append('<li class="weui_uploader_file" data-id="'+data.data.id+'" style="margin-right:0;margin-bottom:16px;position: relative;"><div class="img-del" onclick="imgDel(this)"><span class="icon icon-26"></span></div><img onclick="imgClick(this)" src="'+ imgUrl + data.data.attachmentUrl +'"/></li>'); 
				}
			}, error:function(){
				alert("上传异常");
				}
		});
	}
	
</script>
</html>